//
//  BBWriteLinkViewController.swift
//  BBLinkiOSProject
//
//  Created by liuzhu on 2018/12/7.
//  Copyright © 2018 liuzhu. All rights reserved.
//

import UIKit
import SVProgressHUD
class BBWriteLinkViewController: UIViewController,UITextViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationController?.title = "Edit a link"
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "Send", style: UIBarButtonItem.Style.plain, target: self, action: #selector(sendAction))
    }

    @objc private func sendAction(){
        if contentTV.text.isEmpty {
            SVProgressHUD.showError(withStatus: "Content is not allowed to be empty")
        }
        SVProgressHUD.show()
        let path = "link/send.do"
        let params = ["token":BBUser.loadUser()?.token,"userId":BBUser.loadUser()?.userId,"description":contentTV.text,"linkType":"1","linkImage":"0","usedTime":"0","times":"0","mileage":"0"] as [String : Any]
        var data = Data()
        if linkImage.tag == 1{
            let imageTem = compressImageSize(linkImage.image!, toByte: 50*1024)
            data = imageTem.pngData()!
        }
        AFNetWorkManager.shareNetworkTools().post(path, parameters: params, constructingBodyWith: { (fromData) in
            fromData.appendPart(withFileData: data ?? Data(), name: "upload_file", fileName: "png", mimeType: "application/octet-stream")
        }, progress: { (nil) in
            
        }, success: { (_, json) in
            SVProgressHUD.dismiss()
            SVProgressHUD.showSuccess(withStatus: "Share it to link,Success!")
        }) { (_, error) in
            SVProgressHUD.dismiss()
            SVProgressHUD.showSuccess(withStatus: "Share it to link,Failed!")
        }
    }

    @IBOutlet weak var contentTV: UITextView!
    
    @IBOutlet weak var linkImage: UIImageView!
    
    func textViewDidBeginEditing(_ textView: UITextView) {
        textView.text = ""
    }
    
    @IBAction func addImageAction(_ sender: Any) {
         present(selectorController, animated: true, completion: nil)
    }
    
    // MARK: 用于弹出选择的对话框界面
    var selectorController: UIAlertController {
        let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        controller.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil)) // 取消按钮
        controller.addAction(UIAlertAction(title: "拍照选择", style: .default) { action in
            self.selectorSourceType(type:.camera)
        }) // 拍照选择
        controller.addAction(UIAlertAction(title: "相册选择", style: .default) { action in
            self.selectorSourceType(type:.photoLibrary)
        }) // 相册选择
        return controller
    }
    
    func selectorSourceType(type: UIImagePickerController.SourceType) {
        let vc = UIImagePickerController()
        vc.delegate = self
        vc.sourceType = type
        // 打开图片选择器
        present(vc, animated: true, completion: nil)
    }
    
    private func compressImageSize(_ image: UIImage, toByte maxLength: Int) -> UIImage {
        guard var data = image.jpegData(compressionQuality: 1) else { return image }
        var resultImage: UIImage = image
        var lastDataLength: Int = 0
        while data.count > maxLength, data.count != lastDataLength {
            lastDataLength = data.count
            let ratio: CGFloat = CGFloat(maxLength) / CGFloat(data.count)
            let size: CGSize = CGSize(width: Int(resultImage.size.width * sqrt(ratio)),
                                      height: Int(resultImage.size.height * sqrt(ratio)))
            UIGraphicsBeginImageContext(size)
            resultImage.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
            resultImage = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()
            data = resultImage.jpegData(compressionQuality: 1)!
        }
        return resultImage
    }
}

extension BBWriteLinkViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    // MARK: 图片选择器界面
    var imagePickerController: UIImagePickerController {
        get {
            let imagePicket = UIImagePickerController()
            imagePicket.delegate = self
            imagePicket.sourceType = .photoLibrary
            return imagePicket
        }
    }
    
    // MARK: 当图片选择器选择了一张图片之后回调
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        dismiss(animated: true, completion: nil) // 选中图片, 关闭选择器...这里你也可以 picker.dismissViewControllerAnimated 这样调用...但是效果都是一样的...
        linkImage.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage // 显示图片
        linkImage.contentMode = .scaleAspectFit // 缩放显示, 便于查看全部的图片
        linkImage.tag = 1
    }
    
    // MARK: 当点击图片选择器中的取消按钮时回调
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil) // 效果一样的...
    }
}
